**********************************************************
***** DEFINE PROGRAM FOR KERNEL-WEIGHTED RD GRAPHS *******
**********************************************************

program rdgraph, eclass

syntax varlist(min=2 max=2), pos(integer) [name(string) title(string) ytitle(string) xtitle(string) legend(string) yaxisopt(string)]

token `varlist'
local outcome `1'
local rvar `2'

local nbins 20 // set nbins to fix number of bins on each side. leave empty for letting cmogram command automatically select it (which might be different on the two sides) //
local x_lrange -20
local x_rrange 20

local xaxis_lrange -20
local xaxis_rrange 20

qui rdbwselect `outcome' `rvar', all
local CCT_bw = e(h_mserd)

display "Kernel-weighted RD Graph. Outcome: `outcome'. Running variable: `rvar'. Opt.Bdw:`CCT_bw'. Bins: `nbins'"

local fitted_options "ker(tri) deg(1) lpattern(solid) lcolor(black) lwidth(0.25) ytitle("`ytitle'", size(medlarge)) xtitle("`xtitle'", size(medlarge)) xlabel(`xaxis_lrange'(5)`xaxis_rrange') `yaxisopt' "

if ("`legend'"=="yes") {
	local legend 	"legend(on region(lstyle() fcolor(none) color()) size(medlarge) order(1 3) pos(`pos') ring(0) col(1) lab(1 "Local averages") lab(3 "Fitted"))"
}
else {
	local legend "legend(off)"
	}
	
cmogram `outcome' `rvar' if `rvar'>`x_lrange' & `rvar'<`x_rrange', cutpoint(0) scatter line(0) generate(loc)  histopts(bin(`nbins'))
scatter locy0 locx0, msymbol(Oh) mlcolor(gray) mcolor(gs10) msize() `legend' name(`name') || ///
scatter locy1 locx1, msymbol(Oh) mlcolor(gray) xline(0, lstyle(color(cranberry)) lpattern(dash))  mcolor(gs10) msize()  || ///
lpoly `outcome' `rvar' if `rvar'<0 & `rvar'>`x_lrange' & `rvar'<`x_rrange', bwidth(`CCT_bw')  `fitted_options' || ///
lpoly `outcome' `rvar' if `rvar'>=0 & `rvar'>`x_lrange' & `rvar'<`x_rrange', bwidth(`CCT_bw')  `fitted_options'
	
end
